import { create } from "zustand";
import { AccountType, UserInfoType } from "../types/user";
import { roleGet, userLogin } from "@/api/user";
import { NavigateFunction } from "react-router-dom";
import { persist } from "zustand/middleware";
interface AccountStateType {
  userInfo: null | UserInfoType;
  loading: boolean;
  loginFetch: (arg: AccountType, navigate: NavigateFunction) => void;
  logout: () => void;
}
export const useAccount = create<AccountStateType>()(
  persist(
    (set) => ({
      userInfo: null,
      loading: false,
      loginFetch: async (account, navigate) => {
        set({ loading: true });
        let res = await userLogin(account); //发起登录请求
        let { roleId } = res.data;
        let role = await roleGet(roleId); //使用角色id，获取角色权限数据
        set({ userInfo: { ...res.data, ...role.data }, loading: false });
        navigate("/");
      },
      logout: () => {
        set({ userInfo: null });
      },
    }),
    {
      name: "react-userinfo-2304",
    }
  )
);
